$(function () {
    layui.use(['table', 'element', 'form'], function () {
        var table = layui.table
        var element = layui.element
        var form = layui.form;

        //添加选项（单选题）
        $('div.questions button.add').click(function () {
            var len = $('.layui-tab-item.layui-show .questions').length
            var _char = String.fromCharCode(len + 65);
            $(this).parent().parent().parent()
                .append('<div class="questions">\n' +
                    '    <div class="float-left">\n' +
                    '        <input type="radio" name="answer" value="' + _char + '" title="' + _char + '" class="radio-input"><div class="layui-unselect layui-form-radio"><i class="layui-anim layui-icon"></i><div>' + _char + '</div></div>\n' +
                    '    </div>\n' +
                    '    <div class="txt float-left"><input type="text" datatype="*" nullmsg="选项内容不能为空！" style="width: 573px;"></div>\n' +
                    '    <!-- 这是删除按钮样式 start -->\n' +
                    '    <div class="btn float-left">\n' +
                    '        <button type="button" class="del"></button>\n' +
                    '    </div>\n' +
                    '    <!-- 这是删除按钮样式 end -->\n' +
                    '    <div class="clear"></div>\n' +
                    '</div>')
            form.render()
        })

        //添加选项（多选题）
        $('div.questions button.addM').click(function () {
            var len = $('.layui-tab-item.layui-show .questions').length;
            var _char = String.fromCharCode(len + 65);
            $(this).parent().parent().parent()
                .append('<div class="questions">\n' +
                    '    <div class="float-left">\n' +
                    '        <input type="checkbox" name="answer" value="' + _char + '" title="' + _char + '" class="radio-input" lay-skin="primary"><div class="layui-unselect layui-form-checkbox" lay-skin="primary"><span>' + _char + '</span><i class="layui-icon layui-icon-ok"></i></div>\n' +
                    '    </div>\n' +
                    '    <div class="txt float-left"><input type="text" datatype="*" nullmsg="选项内容不能为空！" style="width: 573px;"></div>\n' +
                    '    <!-- 这是删除按钮样式 start -->\n' +
                    '    <div class="btn float-left">\n' +
                    '        <button type="button" class="delM"></button>\n' +
                    '    </div>\n' +
                    '    <!-- 这是删除按钮样式 end -->\n' +
                    '    <div class="clear"></div>\n' +
                    '</div>');
            form.render()
        });

        //删除选项（单选题）
        $('form#addTopicFormSingle').on('click', '.questions .del', function () {
            $(this).parent().parent().remove();
            $('form#addTopicFormSingle .questions').each(function (index) {
                var inputSi = $(this).find('input[name="answer"]')
                var _char = String.fromCharCode(index + 65)
                $(this).find('input[name="answer"]').val(_char)
                $(this).find('input[name="answer"]').attr('title', _char)
                $(this).find('input[name="answer"]').next().find('div').html(_char)
            })
        })

        //删除选项（多选题）
        $('form#addTopicFormMulti').on('click', '.questions .delM', function () {
            console.log(1)
            $(this).parent().parent().remove();
            $('form#addTopicFormMulti .questions').each(function (index) {
                var inputSi = $(this).find('input[name="answer"]')
                var _char = String.fromCharCode(index + 65)
                $(this).find('input[name="answer"]').val(_char)
                $(this).find('input[name="answer"]').attr('title', _char)
                $(this).find('input[name="answer"]').next().find('span').html(_char)
            })
        })

        //知识点处+号按下
        $('.add-topic .qkadd').on('click', function () {
            layer.open({
                type: 1,
                title: '选择知识点',
                content: $('#select-konwleg'),
                offset: '30px',
                area: ['600px', '565px']
            })
            $.ajax({
                url: '/KnowledgeManager/getKnowledgeList',
                method: 'post',
                contentType: 'application/json;charset=UTF-8',
                data: '{"page": 1, "limit": 100}',
                success: function (result) {
                    const select = $('select[name=zid]').empty()
                    JSON.parse(result).data.forEach(value => select.append('<option value=\"' + value.id + '\">' + value.name + '</option>'))
                    select.change(function (e) {
                        reloadKnowTable()
                    })
                    initKnowTable()
                },
                error: function () {
                    layer.msg('获得数据失败')
                }
            })
            $('#addKnowButton').on('click', function () {
                var checkStatus = table.checkStatus('selectKnowTable');
                if (checkStatus.data.length !== 1) {
                    layer.msg('请选择一个知识点')
                    return
                }
                var knowSp = $('div.layui-tab-item.layui-show td[name="td_knowledge"] > span.qklist')
                knowSp.remove()
                var tdk = $('div.layui-tab-item.layui-show td[name="td_knowledge"]')
                tdk.append('<span class="qklist" val=' + checkStatus.data[0].kid + '>' + checkStatus.data[0].kname + '</span>')
                knowSp.on('click', function () {
                    $('#td_knowledge > span.qklist').remove()
                })
                $('div.layui-tab-item.layui-show td[name="td_knowledge"] input[name="name"]').val(checkStatus.data[0].name)
                $('div.layui-tab-item.layui-show td[name="td_knowledge"] input[name="knowname"]').val(checkStatus.data[0].kname)
            })
            $('button#searchbtn').on('click', function () {
                var zid = $('select[name=zid]').val()
                var key = $('input.search-input[name=key]').val()
                reloadKnowTable({search:{zid:zid,key:key}})
            })
        })

        function initKnowTable() {
            table.render({
                elem: '#selectKnowTable',
                url: '/KnowledgeManager/seeKnowledge', //数据接口
                page: true,
                method: 'post',
                contentType: 'application/json;charset=UTF-8',
                cols: [
                    [
                        {type: 'checkbox', fixed: 'left', width: 50},
                        {field: 'kname', title: '知识点'},
                        {field: 'name', title: '所属岗位'},
                    ],
                ],
                parseData: (value) => {
                    return {
                        "code": value.status - 1,
                        "msg": value.msg,
                        "count": value.page.total,
                        "data": value.data,
                    }
                }
            })
        }

        function reloadKnowTable(params) {
            if (!params) {
                params = {}
            }
            table.reload('selectKnowTable', {where:params})
        }


        //实例化编辑器
        var editor;
        KindEditor.ready(function (K) {
            editor = K.create('#myEditor', {
                /* resizeType: 1,*/
                items: [
                    'source', '|', 'undo', 'redo', '|', 'preview', 'print', 'template', 'cut', 'copy', 'paste',
                    'plainpaste', 'wordpaste', 'wordpaster', '|', 'justifyleft', 'justifycenter', 'justifyright',
                    'justifyfull', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent', 'subscript',
                    'superscript', 'clearhtml', 'quickformat', 'selectall', '|', 'fullscreen', '/',
                    'formatblock', 'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold',
                    'italic', 'underline', 'strikethrough', 'lineheight', 'removeformat', '|', 'image',
                    'flash', 'media', 'insertfile', 'table', 'hr', 'emoticons', 'map', 'code', 'pagebreak',
                    'link', 'unlink', '|', 'about'],
                afterCreate: function () {
                    pasterMgr.SetEditor(this);
                    var self = this;
                    KindEditor.ctrl(self.edit.doc, 'V', function () {
                        pasterMgr.Paste();
                    });
                },
                afterBlur: function () {
                    this.sync()
                }
            })
        })


        //单选题提交
        $('button#addTopicSaveSingle.save').on('click', function () {
            var data = $('#addTopicFormSingle').serializeArray()
            var kid = getKid()
            var options = $('#addTopicFormSingle div.questions > div.txt.float-left > input').map((index, e) => e.value).toArray()
            if (!kid) {
                layer.msg('知识点不能为空')
                return;
            }
            if (!data) {
                layer.msg('题目内容不能为空')
            }
            var names = getFromHidden()
            $.ajax({
                url: '/TopicManager/editTopic',
                method: 'post',
                contentType: 'application/json;charset=UTF-8',
                data: JSON.stringify({
                    type: '单项选择题',
                    kid: kid,
                    difficulty: getFromKv(data, 'level'),
                    data: getFromKv(data, 'conts'),
                    choose: getFromKv(data, 'answer'),
                    answer: getFromKv(data, 'Analysis'),
                    options: JSON.stringify(options),
                    name: getFromKv(data, 'conts'),
                    path: names.knowname,
                    state: document.topic.state,
                    id: document.topic.id,
                }),
                success: function (result) {
                    if (JSON.parse(result).status === 1) {
                        layer.msg('单项选择题编辑成功')
                    } else {
                        layer.msg('错误')
                    }
                },
                error: function () {
                    layer.msg('错误')
                }
            })
        })

        //不定项提交
        $('button#addTopicSaveMulti.save').on('click', function () {
            addTopicFormMulti
            var data = $('#addTopicFormMulti').serializeArray()
            var kid = getKid()
            var options = $('#addTopicFormMulti div.questions > div.txt.float-left > input').map((index, e) => e.value).toArray()
            if (!kid) {
                layer.msg('知识点不能为空')
                return;
            }
            if (!data) {
                layer.msg('题目内容不能为空')
            }
            var names = getFromHidden()
            $.ajax({
                url: '/TopicManager/editTopic',
                method: 'post',
                contentType: 'application/json;charset=UTF-8',
                data: JSON.stringify({
                    // name:,
                    type: '不定项选择题',
                    kid: kid,
                    difficulty: getFromKv(data, 'level'),
                    data: getFromKv(data, 'conts'),
                    choose: getFromKv(data, 'answer'),
                    answer: getFromKv(data, 'Analysis'),
                    options: JSON.stringify(options),
                    name: names.name,
                    path: names.knowname,
                    state: document.topic.state,
                    id: document.topic.id,
                }),
                success: function (result) {
                    if (JSON.parse(result).status === 1) {
                        layer.msg('不定项选择题添加成功')
                    } else {
                        layer.msg('错误')
                    }
                },
                error: function () {
                    layer.msg('错误')
                }
            })

        })

        //填空题提交
        $('button#addTopicSaveBlank.save').on('click', function () {
            var kid = getKid()
            var difficulty = $('#addTopicFormBlank  select[name="level"]').val()
            var data = $('#myEditor3').val()
            var answer = $('#addTopicFormBlank textarea[name="Analysis"]').val()

            if (!kid) {
                layer.msg('知识点不能为空')
                return;
            }
            if (!data) {
                layer.msg('题目内容不能为空')
            }
            var names = getFromHidden()
            $.ajax({
                url: '/TopicManager/editTopic',
                method: 'post',
                contentType: 'application/json;charset=UTF-8',
                data: JSON.stringify({
                    // name:,
                    type: '填空题',
                    kid: kid,
                    difficulty: difficulty,
                    data: data,
                    answer: answer,
                    name: names.name,
                    path: names.knowname,
                    state: document.topic.state,
                    id: document.topic.id,
                }),
                success: function (result) {
                    if (JSON.parse(result).status === 1) {
                        layer.msg('填空题编辑成功')
                    } else {
                        layer.msg('错误')
                    }
                },
                error: function () {
                    layer.msg('错误')
                }
            })
        })

        //判断题提交
        $('button#addTopicSaveCorr.save').on('click', function () {
            var data = $('#addTopicFormCorr').serializeArray()
            var kid = getKid()

            if (!kid) {
                layer.msg('知识点不能为空')
                return;
            }
            if (!data) {
                layer.msg('题目内容不能为空')
            }
            var names = getFromHidden()
            $.ajax({
                url: '/TopicManager/editTopic',
                method: 'post',
                contentType: 'application/json;charset=UTF-8',
                data: JSON.stringify({
                    // name:,
                    type: '判断正误题',
                    kid: kid,
                    difficulty: getFromKv(data, 'level'),
                    data: getFromKv(data, 'conts'),
                    answer: getFromKv(data, 'Analysis'),
                    choose: getFromKv(data, 'answer'),
                    name: names.name,
                    path: names.knowname,
                    state: document.topic.state,
                    id: document.topic.id,
                }),
                success: function (result) {
                    if (JSON.parse(result).status === 1) {
                        layer.msg('判断正误题编辑成功')
                    } else {
                        layer.msg('错误')
                    }
                },
                error: function () {
                    layer.msg('错误')
                }
            })
        })

        //简答题提交
        $('button#addTopicSaveSaq.save').on('click', function () {
            var kid = getKid()
            var difficulty = $('#addTopicFormSaq  select[name="level"]').val()
            var data = $('#myEditor5').val()
            var answer = $('#addTopicFormSaq textarea[name="Analysis"]').val()

            if (!kid) {
                layer.msg('知识点不能为空')
                return;
            }
            if (!data) {
                layer.msg('题目内容不能为空')
            }
            var names = getFromHidden()
            $.ajax({
                url: '/TopicManager/editTopic',
                method: 'post',
                contentType: 'application/json;charset=UTF-8',
                data: JSON.stringify({
                    // name:,
                    type: '简答题',
                    kid: kid,
                    difficulty: difficulty,
                    data: data,
                    answer: answer,
                    name: names.name,
                    path: names.knowname,
                    state: document.topic.state,
                    id: document.topic.id,
                }),
                success: function (result) {
                    if (JSON.parse(result).status === 1) {
                        layer.msg('简答题编辑成功')
                    } else {
                        layer.msg('错误')
                    }
                },
                error: function () {
                    layer.msg('错误')
                }
            })
        })

        //综合题提交
        $('button#addTopicSaveComp.save').on('click', function () {
            var kid = getKid()
            var difficulty = $('#addTopicFormComp  select[name="level"]').val()
            var data = $('#myEditor6').val()
            var answer = $('#addTopicFormComp textarea[name="Analysis"]').val()

            if (!kid) {
                layer.msg('知识点不能为空')
                return;
            }
            if (!data) {
                layer.msg('题目内容不能为空')
            }
            var names = getFromHidden()
            $.ajax({
                url: '/TopicManager/editTopic',
                method: 'post',
                contentType: 'application/json;charset=UTF-8',
                data: JSON.stringify({
                    // name:,
                    type: '综合题',
                    kid: kid,
                    difficulty: difficulty,
                    data: data,
                    answer: answer,
                    name: names.name,
                    path: names.knowname,
                    state: document.topic.state,
                    id: document.topic.id,
                }),
                success: function (result) {
                    if (JSON.parse(result).status === 1) {
                        layer.msg('综合题编辑成功')
                    } else {
                        layer.msg('错误')
                    }
                },
                error: function () {
                    layer.msg('错误')
                }
            })
        })

        //从[{'name':,'value':}]中获得name对应value
        function getFromKv(kv, key) {
            try {
                // var entry = kv.filter(a => a.name === key)[0]
                // return entry ? entry['value'] : null
                return kv.filter(a => a.name === key).reduce(function (total, currVal) {
                    return total + (currVal['value'] ? ',' + currVal['value'] : '')
                }, '').slice(1)
            } catch (e) {
                console.log(e)
                return null
            }
        }

        function getFromHidden() {
            var name = $('div.layui-tab-item.layui-show td[name="td_knowledge"] input[name="name"]').val()
            var knowname = $('div.layui-tab-item.layui-show td[name="td_knowledge"] input[name="knowname"]').val()
            return {"name":name, "knowname":knowname}
        }

        function getKid() {
            return $('div.layui-tab-item.layui-show td[name="td_knowledge"] > span.qklist').attr('val')
        }

        /**********编辑**********/
        var data = document.topic
        switch (data.type) {
            case '单选选择题':
                $('#content > div > ul > li:nth-child(1)').click()
                break
            case '不定项选择题':
                $('#content > div > ul > li:nth-child(2)').click()
                break
            case '填空题':
                $('#content > div > ul > li:nth-child(3)').click()
                break
            case '判断正误题':
                $('#content > div > ul > li:nth-child(4)').click()
                break
            case '简答题':
                $('#content > div > ul > li:nth-child(5)').click()
                break
            case '综合题':
                $('#content > div > ul > li:nth-child(6)').click()
                break
        }
        $('#content > div > ul').css('pointer-events', 'none')
        var td_knowledge = $('.layui-show td[name="td_knowledge"]')
        td_knowledge.find('input[name="name"]').val(data.name)
        td_knowledge.find('input[name="knowname"]').val(data.path)
        td_knowledge.append('<span class="qklist" val="' + data.kid + '">' + data.path + '</span>')
        $('.layui-show select[name="level"]').val(data.difficulty)
        layui.form.render()
        $('.layui-show textarea[name="conts"]').val(data.data)
        $('.layui-show textarea[name="Analysis"]').val(data.answer)
        switch (data.type) {
            case '单项选择题':
                var options = JSON.parse(data.options)
                moreOptions(options)
                fillinoptions(options)
                $('.layui-show .questions div.layui-form-radio div').filter(function(a,b){return $(b).html() === data.choose}).click()
                break
            case '不定项选择题':
                var options = JSON.parse(data.options)
                moreOptions(options)
                fillinoptions(options)
                var chooses = data.choose.split(',')
                $('.layui-show .questions span').filter(function(a,b){
                    return chooses.some(function(c){return $(b).html() === c})
                }).click()
                break
            case '填空题':
                break
            case '判断正误题':
                var index = data.choose === '正确' ? 0 : 1
                $('#addTopicFormCorr > table > tbody > tr:nth-child(4) > td:nth-child(2) > div > div')[index].click()
                break
            case '简答题':
                break
            case '综合题':
                break
        }

        function moreOptions(options) {
            if (options.length > 3) {
                var count = options.length - 3
                while (count-- > 0) {
                    $('.layui-show button.add').click()
                    $('.layui-show button.addM').click()
                }
            }
        }
        function fillinoptions(options) {
            $('.layui-show .questions div.txt input').each(function (index, input) {
                $(input).val(options[index])
            })
        }
    })
})